import { Button, Form, Input, InputNumber, message } from 'antd';
import an58 from '@mmstudio/an000058';
import { Message as M1, Result as R1 } from '../../api/admin/menu/edit.api';
import api from '../../../atoms/api';
import IconButton from '../../../components/iconbutton';
import Uploader from '../../../components/uploader';
import { ITbfdmenuTree } from './content';

export default function Edit({
	data,
	onSave,
	onChange
}: {
	data: ITbfdmenuTree;
	onSave(v: ITbfdmenuTree): void;
	onChange(k: keyof M1, v: string | number): void;
}) {
	return <>
		<Form.Item required label="菜单名称:">
			<Input placeholder='菜单名称' disabled={!data} value={data && data.name} onChange={(e) => {
				onChange('name', e.target.value);
			}} />
		</Form.Item>
		<Form.Item label="显示优先级:">
			<InputNumber placeholder='显示优先级' disabled={!data} value={data && data.weight} onChange={(v) => {
				onChange('weight', v);
			}} />
		</Form.Item>
		<Form.Item label="页面地址:">
			<Input placeholder='页面地址' disabled={!data} value={data && data.url} onChange={(e) => {
				onChange('url', e.target.value);
			}} />
		</Form.Item>
		<Form.Item label={<span title={'每一位表示页面上一个功能（通常为按钮）是否可用，比如0b01表示第一个功能可用,0b11表示第一和第二个功能可用，而0b10表示第二个功能可用，第一个功能不可用'}>用户控制码</span>}>
			<InputNumber placeholder='显示优先级' disabled={!data} value={data && data.control} onChange={(v) => {
				onChange('control', v);
			}} />
		</Form.Item>
		<Form.Item label="菜单图标">
			<div>
				{data && data.icon && <IconButton img={data && data.icon} />}
				{data && <Uploader
					multiple={false}
					type='image'
					height='7rem'
					onChange={(filepath) => {
						onChange('icon', filepath);
					}}
				/>}
			</div>
		</Form.Item>
		<div className='save'>
			<Button disabled={!data} type='primary' onClick={async () => {
				if (!data
					|| !data && data.menuid
					|| !data && data.name
				) {
					message.error('缺少必要的参数');
					return;
				}
				const { children, ...rest } = data;
				const res = await an58<R1, M1>(api['/api/admin/menu/edit'], 'post', rest);
				if (res.ok === false) {
					message.error(res.message);
				} else {
					onSave(data);
				}
			}}>保存</Button>
		</div>
		<style jsx>{`
.save{
display: flex;
flex-direction: row;
justify-content: center;
}
`}</style>
	</>;
}
